package org.gdpu.action;

import com.opensymphony.xwork2.ModelDriven;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.gdpu.base.PageView;
import org.gdpu.model.BloodBank;
import org.gdpu.model.BloodOrder;
import org.gdpu.service.BloodBankService;
import org.gdpu.service.BloodNameService;
import org.gdpu.service.BloodSumService;
import org.gdpu.service.BloodTypeService;
import org.gdpu.util.ChangeTime;
import org.gdpu.vo.BloodBankVO;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.regex.Pattern;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 13-11-8
 * Time: 下午3:28
 * To change this template use File | Settings | File Templates.
 */
@Component("bloodBank")
@Scope("prototype")
public class BloodBankAction extends MyActionSupport implements ModelDriven<BloodBankVO> {
    private final static Logger logger = LogManager.getLogger(BloodBankAction.class);
    private final BloodBankVO bloodBankVO = new BloodBankVO();
    private List<BloodBank> bbs = new ArrayList<BloodBank>();
    private BloodBankService bloodBankService;
    private BloodTypeService bloodTypeService;
    private BloodSumService bloodSumService;
    private BloodNameService bloodNameService;
    private BloodBank bloodBank = new BloodBank();

    public String addBlood() throws Exception {
        if ("".equals(bloodBankVO.getBloodType()) || !IsDigital(bloodBankVO.getBloodVolume()) || "".equals(bloodBankVO
                .getDepartment()) || "".equals(bloodBankVO
                .getBloodPerson()) || "".equals(bloodBankVO
                .getBloodCollection()) || "".equals(bloodBankVO
                .getBloodDate())) {
            bloodBankVO.setResultMessage("请填写完整相关信息!");
            return ERROR;
        }
        bloodBank.setBloodType(bloodTypeService.findTypeName(bloodBankVO.getBloodType()));
        bloodBank.setBloodVolume(Double.parseDouble(bloodBankVO.getBloodVolume()));
        bloodBank.setDepartment(bloodBankVO.getDepartment());
        bloodBank.setBloodPerson(bloodBankVO.getBloodPerson());
        bloodBank.setBloodCollection(bloodBankVO.getBloodCollection());
        Date BloodDate = ChangeTime.parseShortDate(bloodBankVO.getBloodDate());
        bloodBank.setBloodDate(BloodDate);
        bloodBank.setBloodName(bloodNameService.findByName(bloodBankVO.getBloodName()));
        bloodBank.setState(0);
        try {
            bloodBankService.save(bloodBank);
            bloodSumService.bloodVolume(bloodBankVO.getBloodType(), Double.parseDouble(bloodBankVO.getBloodVolume()), true);
            bloodBankVO.setResultMessage("血库录入成功！");
            logger.trace("add a blood record");
        } catch (Exception e) {
            logger.trace(e);
            bloodBankVO.setResultMessage("血库录入有误！");
            return ERROR;
        }
        return SUCCESS;
    }


    public String loadAllBlood() throws Exception {
        /** 每页显示的结果数 **/
        int maxResult = 10;
        /** 封装的页面数据 **/
        PageView<BloodBank> pageView = new PageView<BloodBank>(maxResult, bloodBankVO.getPageNow());
        int firstIndex = ((pageView.getCurrentPage() - 1) * pageView.getMaxResult());// 开始索引
        // 按照条件排序
        LinkedHashMap<String, String> orderBy = new LinkedHashMap<String, String>();
        orderBy.put("state", "asc");
        orderBy.put("overdue", "asc");
        /** 列表条件 **/
        StringBuffer jpql = new StringBuffer("1=1");
        /** 列表条件的值 **/
        List<Object> params = new ArrayList<Object>();
        if ("review".equals(bloodBankVO.getRedirect())) {
            jpql.append(" and o.state = 0");
            view = "/page/bloodBank/bloodBankReView.jsp";
        } else if ("overdue".equals(bloodBankVO.getRedirect())) {
            jpql.append(" and (o.state = 3 or o.state = 1)");
            view = "/page/bloodBank/bloodBankOverdue.jsp";
        } else {
            jpql.append(" and o.state != 0 and (o.state = 2");
            jpql.append(" or (o.overdue > ?").append((params.size() + 1)).append(" and o.state = 1))");
            params.add(new Date());
            view = "/page/bloodBank/bloodBankList.jsp";
        }
        pageView.setQueryResult(bloodBankService.getScrollData(BloodBank.class, firstIndex, maxResult, jpql.toString(),
                params.toArray(), orderBy));
        bloodBankVO.setPageView(pageView);
        return VIEW;
    }

    public String findBloodByState()  {
        List<BloodBank> bbs = bloodBankService.findBloodByState(bloodBankVO.getBloodState());
        if (bloodBankVO.getBloodState().isEmpty() || bbs.size() == 0){
            bloodBankVO.setResultMessage("该状态没有血库记录。");
            return ERROR;
        }
        double sum = 0.0d;
        for(int i = 0; i<bbs.size(); i++){
            sum+=bbs.get(i).getBloodVolume();
        }
        DecimalFormat df = new DecimalFormat("0.00");
        bloodBankVO.setSum(sum);
        bloodBankVO.getBbs().addAll(bbs);
        logger.info("find bloodBank by state:" + bloodBankVO.getBloodState());
        view = "/page/bloodBank/findBloodByState.jsp";
        return VIEW;
    }

    public String overdue() throws Exception {
        int[] bloodBankIds = bloodBankVO.getBloodBankIds();
        String[] messages = bloodBankVO.getMessages();
        bloodBankService.overdue(bloodBankIds, messages);
        bloodBankVO.setResultMessage("报废血液成功！");
        return SUCCESS;
    }

    public String review() throws Exception {
        int[] bloodBankIds = bloodBankVO.getBloodBankIds();
        bloodBankService.review(bloodBankIds, 1);
        bloodBankVO.setResultMessage("审核血液成功！");
        return SUCCESS;
    }

    @Resource(name = "bloodBankServiceImpl")
    public void setBloodBankService(BloodBankService bloodBankService) {
        this.bloodBankService = bloodBankService;
    }

    @Resource(name = "bloodTypeServiceImpl")
    public void setBloodTypeService(BloodTypeService bloodTypeService) {
        this.bloodTypeService = bloodTypeService;
    }

    @Resource(name = "bloodSumServiceImpl")
    public void setBloodSumService(BloodSumService bloodSumService) {
        this.bloodSumService = bloodSumService;
    }

    @Resource(name = "bloodNameServiceImpl")
    public void setBloodNameService(BloodNameService bloodNameService) {
        this.bloodNameService = bloodNameService;
    }

    @Override
    public BloodBankVO getModel() {
        return bloodBankVO;
    }

    //判断输入字符串能否转为double类型
    private boolean IsDigital(String str) {
        Pattern pattern = Pattern.compile("-?[^\\D]+\\.?[^\\D]+");
        return pattern.matcher(str).matches();
    }
}
